package com.link_with_health.controller;

import com.link_with_health.common.Result;
import com.link_with_health.common.TokenMap;
import com.link_with_health.exception.BaseException;
import com.link_with_health.exception.NullQueryResultException;
import com.link_with_health.model.DepartmentsEntity;
import com.link_with_health.model.UserEntity;
import com.link_with_health.service.DepartmentsService;
import com.link_with_health.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/api/department")
public class DepartmentController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final String AUTH_TOKEN = "Authorization";
    private TokenMap tokenMap = TokenMap.getInstance();

    @Resource(name = "departmentsService")
    DepartmentsService departmentsService;

    /**
     * 获取科室信息
     * @param json 数据
     * @param request 请求
     * @return 结果
     */
    @RequestMapping("/findDepartmentInfo")
    @ResponseBody
    public Result findDepartmentInfo(@RequestBody Map<String,Object> json
            , HttpServletRequest request){
        String token = request.getHeader(AUTH_TOKEN);
        System.out.println("is carry token: "+tokenMap.containsKey(token));
        String msg = "请求失败 检验失败";

        try {
            String method = (String) json.get("method");
            HashMap<String,Object> params = (HashMap<String, Object>) json.get("params");
            //根据参数中的查找规则查找数据
            return findDataByMethod(method,params);
        }catch (Exception e){
            logger.error("[request department message failed]",e);
            msg="数据获取失败";
            if(e instanceof NullQueryResultException){
                return Result.notResult("无查询结果","NULL");
            }
        }


        return Result.fail(msg);
    }

    /**
     * 获取所有的科室信息（作用于左侧表，父类嵌套子类）
     * @param request 请求
     * @return 数据结果
     */
    @GetMapping("/getDepartmentList")
    @ResponseBody
    public Result getDepartmentList(HttpServletRequest request){
        String token = request.getHeader(AUTH_TOKEN);
        System.out.println("is carry token: "+tokenMap.containsKey(token));

        String msg = "请求失败 检验失败";

        if(tokenMap.containsKey(token)) {
            UserEntity entity = (UserEntity) tokenMap.get(token);
            System.out.println(token + " ==> " + entity);
        }

        try {

            ArrayList<HashMap<String,Object>> result = new ArrayList<>();
            for(DepartmentsEntity department : departmentsService.getMainDepartments()){

                Long id = department.getDepartmentId();
                //将大类科室放进数组
                ArrayList<DepartmentsEntity> list = new ArrayList<>();
                list.add(department);

                List<DepartmentsEntity> children = new ArrayList<>();

                try{
                    children = departmentsService
                            .getDepartByParentDepart(id.intValue());
                }catch (Exception e){
                    logger.info("[this department lost children department => "
                            + department.getDepartment() + "]");
                }

                if(children != null && !children.isEmpty())
                    //子科室进队列
                    list.addAll(children);


                HashMap<String,Object> map = JsonUtil.bean2Map(department);
                map.put("children",list);

                //封装进入结果
                result.add(map);
            }
            logger.info("[get all department List success]");
            return Result.success(result);

        } catch(Exception e){
            logger.error("error for req departmentList",e);
            msg = "数据获取失败";
        }

        return Result.fail(msg);
    }

    /**
     * 根据请求中的参数
     * @param method 何种参数查询
     * @param params 查询的参数
     * @return 查询结果
     * @throws Exception 异常
     */
    private Result findDataByMethod(String method
            ,Map<String,Object> params) throws Exception{


        List<DepartmentsEntity> entities = null;

        switch(method){
            case "all": case "all-page":
                entities = findAllDepartments();
                break;
            case "main":
                entities = findMainDepartments();
                break;
            default:
                break;
        }
        if(entities == null|| entities.isEmpty()){
            throw new NullQueryResultException("RESULT OF DEPARTMENT IS NULL");
        }

        //过滤科室名为空的数据
        entities = entities.stream().filter(item
                        -> !(item.getDepartment()  == null
                        || "".equals( item.getDepartment())))
                .collect(Collectors.toList());


        return Result.success(entities);
    }

    /**
     * 查找除名字为null的科室信息
     * @return 返回给前端的数据
     * @throws Exception
     */
    private List<DepartmentsEntity> findAllDepartments()
            throws Exception {
        return departmentsService.getAllDepartments();
    }

    /**
     *查找除名字为null的主科室信息
     * @return
     * @throws Exception
     */
    private List<DepartmentsEntity> findMainDepartments()
            throws Exception{
        return departmentsService.getMainDepartments();
    }

    /**
     * 通过父级科室寻找子级科室
     * @param departmentId
     * @return
     * @throws Exception
     */
    private List <DepartmentsEntity> findParentsDepartments(int departmentId)
            throws Exception{
        return departmentsService.getDepartByParentDepart(departmentId);
    }


}
